package org.finesys.common.tenant.mybatis;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.finesys.common.tenant.properties.TenantProperties;
import org.finesys.common.tenant.support.TenantContextHolder;

import java.util.Objects;


public class TenantDatabaseHandler implements TenantLineHandler {
    private final TenantProperties tenantProperties;

    /**
     * 多租户的配置信息
     *
     * @param tenantProperties 多租户配置
     */
    public TenantDatabaseHandler(TenantProperties tenantProperties) {
        this.tenantProperties = tenantProperties;
    }

    /**
     * 拼接租户条件
     *
     * @return 表达式
     */
    @Override
    public Expression getTenantId() {
        Long tenantId = TenantContextHolder.getTenantId();
        if (Objects.isNull(tenantId)) {
            return new NullValue();
        }
        return new LongValue(tenantId);
    }

    /**
     * 获取租户字段名
     *
     * @return 租户字段名
     */
    @Override
    public String getTenantIdColumn() {
        return tenantProperties.getColumn();
    }

    /**
     * 当前表是否忽略多租户
     *
     * @param tableName 表名
     * @return true or false
     */
    @Override
    public boolean ignoreTable(String tableName) {
        return TenantContextHolder.isIgnore() || !CollUtil.contains(tenantProperties.getIgnoreUrls(), tableName);
    }
}
